package com.yue.yadmin.shiro.realm;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.yue.yadmin.enums.EnumBool;
import com.yue.yadmin.model.SysUser;
import com.yue.yadmin.service.SysUserSerivce;

public class AccountRealm extends AuthorizingRealm {
    @Autowired
    SysUserSerivce sysUserService;

    /**
     * 提供用户信息返回权限信息
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	SysUser sysUser = (SysUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 根据用户名查询当前用户拥有的角色
        List<String> roles = sysUserService.findRoles(sysUser.getId());
        Set<String> roleNames = new HashSet<String>();
        if(roles!=null&&roles.size()>0)roleNames.addAll(roles);
        // 将角色名称提供给info
        authorizationInfo.setRoles(roleNames);
        // 根据用户名查询当前用户权限
        List<String> permissions = sysUserService.findPermissions(sysUser.getId());
        Set<String> permissionNames = new HashSet<String>();
//        if(permissions!=null&&permissions.size()>0)permissionNames.addAll(permissions);
        //一个菜单可能存在多个权限，用逗号隔开
        for(int i=0,total=permissions.size();i<total;i++){
        	String[] perms = permissions.get(i).split(",");
        	for(String perm:perms)permissionNames.add(perm);
        }
        // 将权限名称提供给info
        authorizationInfo.setStringPermissions(permissionNames);

        return authorizationInfo;
    }

    /**
     * 提供账户信息返回认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        SysUser sysUser = new SysUser();
        sysUser.setUsername(username);
        sysUser = sysUserService.get(sysUser);
        if (sysUser == null) {
            // 用户名不存在抛出异常
            throw new UnknownAccountException("用户名不存在");
        }
        if(sysUser.getStatus()==null||EnumBool.TRUE.getCode()!=sysUser.getStatus()){
        	throw new LockedAccountException("账户被禁用");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(sysUser,
        		sysUser.getPassword(), getName());
        return authenticationInfo;
    }
    
}
